package com.apps.ftapp.activity;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.adapter.MyLessonAdapter;
import com.apps.ftapp.model.MyLessonModel;
import com.apps.ftapp.model.TableModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

/**
 * 我的课程
 */
public class MyLessonActivity extends BaseActivity implements View.OnClickListener, MyLessonAdapter.MyClickListener {

    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
//    @BindView(R.id.tebieguanzhu)
//    Button tebieguanzhu;

    @BindView(R.id.guanzhu_lin)
    LinearLayout guanzhu_lin;
    @BindView(R.id.calendar_lin)
    LinearLayout calendar_lin;

    //用于记录当前是第几页
    private int curPage = 1;
    //用于记录一页应该请求多少条数据
    private int pageSize = 10;
    //用于记录总页数，在上拉的时候判断还有没有更多数据
    private boolean isEnd = false;

    private Gson gson = new Gson();

    String tempData = new String();

    private List<MyLessonModel.CourseBean> dataList1 = new ArrayList();

    private MyLessonAdapter myLessonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_lesson);
        ButterKnife.bind(this);

        setTitle("我的课程");
        initView();

        //tebieguanzhu.setOnClickListener(this);

        loadData();
    }

    private void loadData() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("page", curPage);
        Async.get("my/courses", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    MyLessonModel result = gson.fromJson(new String(responseBody), MyLessonModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        dataList1.addAll(result.getCourse());
                        myLessonAdapter.addRes(result.getCourse());
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }

            @Override
            public void onFinish() {
                gettable();
                super.onFinish();
            }
        });

    }

    private void initView() {

        guanzhu_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivitySkipUtil.skipAnotherActivity(MyLessonActivity.this, MyLessonCollActivity.class, false);
            }
        });
        calendar_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toasty.normal(getApplicationContext(), "功能开发中，请稍候~").show();
                Intent intent = new Intent();
                intent.setClass(MyLessonActivity.this, TimeTableActivity.class);
                intent.putExtra("data", tempData);
                startActivity(intent);
                //ActivitySkipUtil.skipAnotherActivity(MyLessonActivity.this, TimeTableActivity.class, false);

            }
        });
        myLessonAdapter = new MyLessonAdapter(getApplicationContext(), new ArrayList<MyLessonModel.CourseBean>(), this);
        listView.setAdapter(myLessonAdapter);

//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                HashMap map = new HashMap();
//                map.put("id", dataList.get(position).getId());
//                map.put("title", dataList.get(position).getTitle());
//                ActivitySkipUtil.skipAnotherActivity(MyLessonActivity.this, MyLessonListActivity.class, map);
//            }
//        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);
                //一般加载数据都是在子线程中，这里我用到了handler
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        curPage = 1;
//                        myOrderAdapter.clearLists()clearLists;
                        loadData();
                    }
                }, 1000);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        isLoadMore = false;
                        curPage = curPage + 1;
                        if (!isEnd) {
                            loadData();
                        } else {
                            Toasty.normal(getApplicationContext(), "没有更多啦O(∩_∩)O").show();

                        }
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
//            case R.id.tebieguanzhu:
//
//
//                ActivitySkipUtil.skipAnotherActivity(MyLessonActivity.this, MyLessonCollActivity.class, false);
//
//                break;

        }

    }

    @Override
    public void clickListener(View v) {

        final int position = (int) v.getTag();
        switch (v.getId()) {
            case R.id.top_container:
                HashMap map = new HashMap();
                map.put("id", dataList1.get(position).getId());
                map.put("title", dataList1.get(position).getTitle());
                map.put("type", dataList1.get(position).getType());
                ActivitySkipUtil.skipAnotherActivity(MyLessonActivity.this, MyLessonListActivity.class, map);
                break;

            case R.id.delete_lin:
                new MaterialDialog.Builder(this)
                        .title(R.string.title1)
                        .content(R.string.delete_course)
                        .contentColor(Color.BLACK)
                        .positiveText(R.string.agree)
                        .positiveColor(Color.BLACK)
                        .negativeColor(Color.BLACK)
                        .negativeText(R.string.disagree)
                        .onAny(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                if (which == DialogAction.NEUTRAL) {
                                } else if (which == DialogAction.POSITIVE) {
                                    deletes(position);
//                          Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                                } else if (which == DialogAction.NEGATIVE) {
                                }

                            }
                        })
                        .show();


                break;

            case R.id.coll_lin:

                coll(position);

                break;
        }
    }


    private void coll(final int i) {

        L.i("main", "收藏////");

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", dataList1.get(i).getId());
        params.put("gz", "1".equals(dataList1.get(i).getMemberfllow()) ? "2" : "1");
        L.i("main", "gz:::" + dataList1.get(i).getMemberfllow());
        Async.post("my/coursesaddv", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    String guanzhu = Tools.isNull(dataList1.get(i).getMemberfllow());
                    Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                    if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                        if ("1".equals(guanzhu)) {
                            dataList1.get(i).setMemberfllow("2");
                            Toasty.normal(getApplicationContext(), "取消收藏").show();
                        } else {
                            dataList1.get(i).setMemberfllow("1");
                            Toasty.normal(getApplicationContext(), "收藏成功").show();
                        }
                        myLessonAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });

    }


    private void deletes(final int i) {


        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", dataList1.get(i).getId());
        L.i("main", dataList1.get(i).getId());
        Async.post("my/coursesdel", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                    if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                        myLessonAdapter.delRes(dataList1.get(i));
                        dataList1.remove(dataList1.get(i));
//                        myLessonAdapter.notifyDataSetChanged();
                        Toasty.normal(getApplicationContext(), "删除成功").show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });

    }

    private void gettable() {
        RequestParams params = new RequestParams();
        params.add("userId", Constant.uid);
        params.add("token", Constant.token);
        Async.post("my/daycron", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    try {
                        TableModel result = gson.fromJson(new String(responseBody), TableModel.class);
                        //1表示红点，0表示灰点  //但是真实的数据时0红点 1灰点
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            if (!result.getLesson_date().equals("") && result.getLesson_date() != null) {
                                tempData = result.getLesson_date();

                            }
                        }

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

}
